import Vue from "vue";
import Router from "vue-router";
import routes from "./router";
import Util from "@/lib/util";
import Config from "@/config/index";
// import Storage from "vue-ls";
import store from "@/store";
const tokenName = Config.request.tokenName;
const util = new Util();

Vue.use(Router);
const router = new Router({
  mode: "hash",
  routes
});

// beforeEach可以注册一个全局前置守卫
router.beforeEach((to, from, next) => {
  let token = window.localStorage.getItem(tokenName);
  // const loginInfo = Vue.ls.get("loginInfo");
  to.meta && util.setTitle(to.meta.title);

  // 判断该路由是否需要登录权限
  if (to.meta.requireAuth) {
    // 获取当前的token是否存在
    if (token) {
      if (!store.state.userInfo) {
        store.dispatch("getUserInfo");
      }
      next();
    } else {
      store.dispatch("logOut");
      next({
        path: "/login",
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else {
    next();
  }
});

export default router;
